package com.ryl.yomall.cart.controller;

import com.ryl.yomall.cart.service.CartInfoService;
import com.ryl.yomall.model.cart.CartInfo;
import com.ryl.yomall.model.common.result.Result;
import com.ryl.yomall.model.common.util.AuthContextHolder;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @Date 13:25
 * @Author ryl
 */
@RestController
@RequestMapping("/api/cart")

public class CartApiController {
    @Autowired
    private CartInfoService cartInfoService;
    //加入购物车
    @GetMapping("/addToCart/{skuId}/{skuNum}")
    public CartInfo addToCart(@PathVariable Long skuId, @PathVariable Integer skuNum
            , HttpServletRequest request){
        String userId = AuthContextHolder.getUserId(request);
        if(StringUtils.isEmpty(userId)){
            //未登录
            userId = AuthContextHolder.getUserTempId(request);
        }
         return cartInfoService.addToCart(skuId,skuNum,userId);
    }
    @GetMapping("/addToCart1/{skuId}/{skuNum}")
    public Result addToCart1(@PathVariable Long skuId, @PathVariable Integer skuNum
            , HttpServletRequest request){
        String userId = AuthContextHolder.getUserId(request);
        if(StringUtils.isEmpty(userId)){
            //未登录
            userId = AuthContextHolder.getUserTempId(request);
        }
        cartInfoService.addToCart1(skuId,skuNum,userId);
        return Result.ok ();
    }
    //查询当前用户的所有购物车
    // 当前用户,可能是临时用户,可能是真实用户
    @GetMapping("/cartList")
    public Result cartList(HttpServletRequest request){
        String userId = AuthContextHolder.getUserId ( request );
        String userTempId = AuthContextHolder.getUserTempId ( request );
        //合并之后的购物车
        List<CartInfo> cartInfoList= cartInfoService.cartList(userId,userTempId);
        return Result.ok (cartInfoList);
    }

    //选中或取消, 购物车
    @GetMapping("/checkCart/{skuId}/{isChecked}")
    public Result checkCart(@PathVariable Long skuId ,@PathVariable Integer isChecked){
        cartInfoService.checkCart(skuId,isChecked);
        return Result.ok ();
    }
    //删除选中
    @DeleteMapping("/deleteChecked")
    public Result deleteChecked(){
        cartInfoService.deleteChecked();
        return Result.ok ();
    }
    @GetMapping("/chooseAll/{isChecked}")
    public Result chooseAll(@PathVariable Integer isChecked){
        cartInfoService.chooseAll(isChecked);
        return Result.ok ();
    }
    @DeleteMapping("deleteCart/{skuId}")
    public Result deleteCart(@PathVariable Long skuId){
        cartInfoService.deleteCart(skuId);
        return Result.ok ();
    }
    //查询选中
    @GetMapping("/findChecked")
    public List<CartInfo> findChecked(HttpServletRequest request){
        String userId = AuthContextHolder.getUserId ( request );

        return cartInfoService.findChecked(userId);
    }

}
